package com.asyf.provider.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "示例接口")
@RestController
@RequestMapping(value = "/")
public class DemoController {

    @Value("${server.port}")
    private Integer port;

    @Value("test")
    private String test;

    @ApiOperation(value = "feign请求示例")
    @RequestMapping(value = "/demo", method = RequestMethod.GET)
    public String test() {
        System.out.println(test.length());
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "abc" + " - port:" + port;
    }

    @ApiOperation(value = "熔断与服务降级示例")
    @RequestMapping(value = "/sentinel", method = RequestMethod.GET)
    @SentinelResource(value = "sentinel", blockHandler = "editBlock", fallback = "editFallback")
//    @SentinelResource(value = "sentinel")
    public Object test2() {
        Date date = new Date();
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        return format;
    }

    // 限流的处理 注意返回值类型需要一样 都是Object
    public Object editBlock(BlockException ex) {
        Map<String, Object> map = new HashMap();
        map.put("msg", "限流了.");
        return map;
    }

    //服务降级的处理方法
    public Object editFallback(Throwable e) {
        Map<String, Object> map = new HashMap();
        map.put("msg", "fallback 服务降级了.");
        return map;
    }
}
